package com.yunc.auth.config.auth;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yunc.auth.domain.UserEntity;
import com.yunc.auth.domain.dto.UserDTO;
import com.yunc.auth.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author taocongcong
 * @create 2020-12-23 14:20
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserDetailsServiceImpl implements UserDetailsService {

    private final ISysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDTO sysUser = sysUserService.getByLoginName(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("未查询到用户");
        }
        // username就是AuthenticationPrincipal用来获取用户的
        UserEntity user = new UserEntity(sysUser.getId(), sysUser.getId(), sysUser.getUserPassword(), true);
        if (StringUtils.isNotBlank(sysUser.getRoleIds())) {
            String[] arr = sysUser.getRoleIds().split(",");
            if (arr != null && arr.length > 0) {
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                for (String roleId : arr) {
                    authorities.add(new SimpleGrantedAuthority(String.valueOf(roleId)));
                }
                user.setAuthorities(authorities);
            }
        }
        return user;
    }
}
